import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import { Form, message, Button, Modal, Input, Popconfirm, Select } from 'antd'
import { widgetType, CHECK_STATUS, ORDER_STATUS, PAY_CHANNEL } from 'constants'
import { getPriceFilter } from 'utils/utils'
import PropTypes from 'prop-types'
import Style from './reconciliation.css'

const { Option } = Select

class IndexForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getOrderAccountList: PropTypes.func,
    accountData: PropTypes.object,
    checkAccount: PropTypes.func,
    reversalAccount: PropTypes.func,
    // restoreGoodsRequest: PropTypes.any,
    listLoading: PropTypes.bool,
    updateReconciliation: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      selectedRowKeys: [],
      showDetail: false,
      currentRow: {},
      // isSingle: true,
      selected: [],
      isEditing: false,
      remark: null,
      checkStatus: null
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.onSelectChange = this.onSelectChange.bind(this)
  }

  getFilterCols () {
    const options = Object.keys(CHECK_STATUS).map(n => {
      return {
        text: CHECK_STATUS[n],
        value: n
      }
    })
    return [
      {
        label: '订单编号',
        id: 'orderNo',
        widget: widgetType.input,
        placeholder: '请输入订单编号'
      }, {
        label: '对账状态',
        id: 'checkStatus',
        widget: widgetType.select,
        placeholder: '请选择',
        options
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '订单编号',
        dataIndex: 'orderNo',
        key: 'orderNo',
        width: 100,
        sorter: (a, b) => a.commodityId - b.commodityId
      },
      {
        title: '订单金额',
        dataIndex: 'orderAmount',
        key: 'orderAmount',
        render: n => `¥${getPriceFilter(n)}`,
        width: 100
      },
      {
        title: '支付方式',
        dataIndex: 'payChannel',
        key: 'payChannel',
        render: n => n ? `${PAY_CHANNEL[n]}` : '',
        width: 100
      },
      {
        title: '支付时间',
        dataIndex: 'payTime',
        key: 'payTime',
        width: 100,
        sorter: (a, b) => a.payTime - b.payTime
      },
      {
        title: '对账人员',
        dataIndex: 'operator',
        key: 'operator',
        width: 100
      },
      {
        title: '对账时间',
        dataIndex: 'operateTime',
        key: 'operateTime',
        width: 100
      },
      {
        title: '状态',
        dataIndex: 'checkStatus',
        key: 'checkStatus',
        render: n => `${CHECK_STATUS[n]}`,
        width: 100
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <a className='a-btn' onClick={() => this.showDetail(record)}>查看详情</a>
          </>
        },
        width: 100
      }
    ]
  }

  showDetail = record => {
    this.setState({
      // isSingle: true,
      showDetail: true,
      currentRow: record,
      checkStatus: record.checkStatus,
      remark: record.remark
    })
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    this.props.getOrderAccountList({
      pageNo: 1,
      pageSize: 20
    })
  }
  search (values = {}) {
    const { pageSize, pageNo } = this.state
    values.pageNo = pageNo
    values.pageSize = pageSize
    this.setState({
      params: values
    })
    this.props.getOrderAccountList(values)
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getOrderAccountList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getOrderAccountList(params)
  }

  onSelectChange (selectedRowKeys, selectedRows) {
    this.setState({
      selected: selectedRows,
      selectedRowKeys
    })
  }

  // 批量还原
  checkAll = () => {
    const { selected } = this.state
    if (selected && selected.length) {
      const ids = selected.map(n => n.id)
      this.checkOk(ids).then(() => {
        this.setState({
          selectedRowKeys: [],
          selected: []
        })
        this.init()
      })
    } else {
      message.warning('请选择需要对账的订单')
    }
  }

  componentDidMount () {
    this.init()
  }

  init = () => {
    const { pageSize, pageNo } = this.state
    this.props.getOrderAccountList({
      pageSize,
      pageNo
    })
  }

  handleSubmit = (id) => {
    const { checkStatus, remark } = this.state
    let msg = ''
    if (!checkStatus || !remark) {
      if (!checkStatus) {
        msg = '请选择对账状态'
      }
      if (!remark) {
        msg = '请填写对账备注'
      }
      message.warning(msg)
    }
    // TODO 调接口
    this.props.updateReconciliation({
      id,
      checkStatus,
      remark
    }).then(() => {
      this.init()
      this.handleCancel()
    })
  }

  handleChangeStatus = (value) => {
    this.setState({
      checkStatus: value
    })
  }

  handleRemark = (value) => {
    this.setState({
      remark: value.target.value
    })
  }

  renderFooter = () => {
    const { currentRow, isEditing } = this.state
    // if (isSingle) { // 单选 - 多选
    const id = currentRow.id
    if (isEditing) {
      return (
        <div>
          <Button onClick={this.handleCancel}>取消</Button>
          <Button type='primary' onClick={() => this.handleSubmit(id)}>确认</Button>
        </div>
      )
    } else {
      return null
    }
    // if (currentRow.checkStatus === '01') { // 未对账
    //   return (
    //     <div>
    //       <Button onClick={this.handleCancel}>取消</Button>
    //       <Button type='primary' onClick={() => this.checkOk(ids)}>对账无误</Button>
    //     </div>
    //   )
    // } else if (currentRow.checkStatus === '02') { // 异常账
    //   return (
    //     <div>
    //       <Button onClick={this.handleCancel}>取消</Button>
    //       <Button type='primary' onClick={() => this.reverse(ids)}>冲正处理</Button>
    //     </div>
    //   )
    // }
    // return null
  }

  // 对账无误
  checkOk = (ids) => {
    this.props.checkAccount({
      ids
    }).then(() => {
      message.success('对账成功')
      this.setState({
        showDetail: false
      })
      this.init()
    })
  }

  // 冲正
  reverse = (ids) => {
    this.props.reversalAccount({
      ids
    }).then(() => {
      message.success('冲正成功')
      this.setState({
        showDetail: false
      })
      this.init()
    })
  }

  handleCancel = () => {
    this.setState({
      showDetail: false,
      isEditing: false,
      checkStatus: null,
      remark: null
    })
  }

  renderDetail = () => {
    const { currentRow, isEditing, checkStatus, remark } = this.state
    return (
      <div className={Style['detail-wrap']}>
        <div className={Style['content']}>
          <div className={Style['title']}>订单信息</div>
          <div className={Style['item']}>
            <div className={Style['label']}>订单编号</div>
            <div className={Style['value']}>{currentRow.orderNo}</div>
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>订单金额</div>
            <div className={Style['value']}>{`¥${getPriceFilter(currentRow.orderAmount)}`}</div>
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>支付方式</div>
            <div className={Style['value']}>{currentRow.payChannel}</div>
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>支付时间</div>
            <div className={Style['value']}>{currentRow.payTime}</div>
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>订单状态</div>
            <div className={Style['value']}>{ORDER_STATUS[currentRow.orderStatus]}</div>
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>是否退款</div>
            <div className={Style['value']}>{currentRow.refundFlag === 1 ? '是' : '否'}</div>
          </div>
        </div>
        <div className={Style['content']}>
          <div className={Style['title']}>对账信息</div>
          <div className={Style['item']}>
            <div className={Style['label']}>对账状态</div>
            <div className={Style['value']}>
              {isEditing ? (
                <Select value={checkStatus} onChange={this.handleChangeStatus} style={{ width: 150 }} placeholder='请选择'>
                  {Object.keys(CHECK_STATUS).map(n => <Option key={n} value={n}>{CHECK_STATUS[n]}</Option>)}
                </Select>
              ) : CHECK_STATUS[currentRow.checkStatus] }
            </div>
            {!isEditing && <a onClick={() => this.setState({ isEditing: true })} className='a-btn'>修改</a>}
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>对账人员</div>
            <div className={Style['value']}>{currentRow.operator || '-'}</div>
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>对账时间</div>
            <div className={Style['value']}>{currentRow.operateTime || '-'}</div>
          </div>
          <div className={Style['item']}>
            <div className={Style['label']}>对账备注</div>
            <div className={Style['value']}>
              {isEditing ? <Input value={remark} onChange={this.handleRemark} style={{ width: '100%' }} placeholder='请输入' /> : `${currentRow.remark || '-'}`}
            </div>
          </div>
        </div>
      </div>
    )
  }

  render () {
    const { pageNo, pageSize, selectedRowKeys, showDetail } = this.state

    const { form, accountData, listLoading } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: accountData && accountData.totalCount,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters
              cols={this.getFilterCols()}
              form={form}
              search={this.search}
              reset={this.reset}
            >
              <Popconfirm onConfirm={this.checkAll} title='确认对账'>
                <Button type='primary' >批量对账</Button>
              </Popconfirm>
            </Filters>
            <CustomTable
              selectedRowKeys={selectedRowKeys}
              multipleSelect={this.onSelectChange}
              multiple
              loading={listLoading} columns={this.getTableCols()}
              dataSource={(accountData && accountData.checkAccountDetialsList) || []}
              pagination={pagination} />
          </div>
          <Modal
            title='对账单信息'
            width={660}
            visible={showDetail}
            onCancel={this.handleCancel}
            footer={
              this.renderFooter()
            }
          >
            {this.renderDetail()}
          </Modal>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  accountData: state.order.accountData,
  listLoading: state.loading.effects.order.getOrderAccountList
})
const mapDispatch = dispatch => ({
  getOrderAccountList: dispatch.order.getOrderAccountList,
  reversalAccount: dispatch.order.reversalAccount,
  checkAccount: dispatch.order.checkAccount,
  updateReconciliation: dispatch.order.updateReconciliation
})

const Index = Form.create()(IndexForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Index)
)
